const express = require("express");
const router = express.Router();
const multer = require("multer");
const path = require("path");
const fileUrl = require("../tools/file");
const ResponseHelper = require("./ResponseHelper");
const fs = require("fs");
const allowedMimetype = [
  "image/jpeg",
  "jpg",
  "jpeg",
  "image/png",
  "image/bmp",
  "gif",
  "video/x-matroska",
];
function fileFilter(req, file, cb) {
  // 这个函数应该调用 `cb` 用boolean值来指示是否应接受该文件
  if (allowedMimetype.includes(file.mimetype)) {
    //接受这个文件，使用`true`，像这样:
    cb(null, true);
  } else {
    // 拒绝这个文件，使用`false`，像这样:
    cb(new Error("Reject this type of picture"));
  }
}

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    const customFolder = req.params.id || "default";
    const fullFolderPath = path.join(fileUrl.imgStaticPath, customFolder);
    // 如果文件夹不存在，则创建它
    if (!fs.existsSync(fullFolderPath)) {
      fs.mkdirSync(fullFolderPath, { recursive: true });
    }
    // 在每次上传前清空目标文件夹
    // fs.readdir(fullFolderPath, (err, files) => {
    //   if (err) throw err;
    //   for (const file of files) {
    //     fs.unlink(path.join(fullFolderPath, file), (err) => {
    //       if (err) throw err;
    //     });
    //   }
    // });
    console.log("+++++++++++++++++++++fullFolderPath", fullFolderPath);
    cb(null, fullFolderPath);
  },
  filename: function (req, file, cb) {
    const fileName = `${req.params.id}_${new Date().getTime()}`;
    let ext = file.mimetype.split("/")[1];
    cb(null, `${fileName}.${ext}`);
  },
});

const upload = multer({
  storage: storage,
  limits: { fileSize: 1024 * 1024 * 10 },
  fileFilter,
});
router.post("/:id", upload.single("file"), (req, res, next) => {
  const save_path = req.params.id;
  // let protocol = req.headers.host.includes("diag.cobotsys.com") ? "https" : "http";
  // console.log("++++++++++++++++++++++++++++++++protocol",protocol)
  console.log("++++++++++++++++++++++++++++++++req.protocol", req.protocol);
  console.log(
    "++++++++++++++++++++++++++++++++req.headers.host",
    req.headers.host
  );
  const host = req.headers.host.includes("host")
    ? "diag.cobotsys.com"
    : req.headers.host;
  const imageUrl = `${req.protocol}://${host}/uploads/${save_path}/${req.file.filename}`;
  res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
  ResponseHelper.sendData(imageUrl, res);
});

module.exports = router;
